package com.example.order.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.example.order.R;
import com.example.order.pojo.Dish;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class WindowMenuFragment extends Fragment {
    private Dish dish;
    TextView titleTextView;
    ListView dishListView;
    Button addDishButton, editButton, deleteButton, refreshButton;
    private static final int GET_FROM_GALLERY = 1;
    private String selectedImagePath;
    private ImageView selectedImageView;  // 新增成员变量
    private boolean isImageSelected = false;

    private String window_id;



    private static final String BASE_URL = "http://10.2.0.232:8080/backend-api-endpoint";

    public WindowMenuFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_window_menu, container, false);



        // Get references to UI elements
        titleTextView = view.findViewById(R.id.titleTextView);
        dishListView = view.findViewById(R.id.dishListView);
        addDishButton = view.findViewById(R.id.addDishButton);
//        editButton = view.findViewById(R.id.editButton);
//        deleteButton = view.findViewById(R.id.deleteButton);
        refreshButton = view.findViewById(R.id.refreshButton);

        // 获取 ImageView 的引用
        selectedImageView = view.findViewById(R.id.selectedImageView);

        // Set ListView choice mode
        dishListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        // 修改 addDishButton.setOnClickListener
        addDishButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 弹出填充框
                showAddDishDialog();

            }
        });

        refreshButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAllDishs();
            }
        });


        Bundle args = getArguments();
        if (args != null) {
            window_id = args.getString("window_id", "");
        }

        // Call the method to get all dishs when the fragment is created
        getAllDishs();

        return view;
    }

    private class GetAllDishsTask extends AsyncTask<Void, Void, List<Dish>> {
        private String window_id;

        public GetAllDishsTask(String windowId) {
            this.window_id = windowId;
        }


        @Override
        protected List<Dish> doInBackground(Void... voids) {
            OkHttpClient client = new OkHttpClient();
//            String url = "http://10.2.2.204:8080/backend-api-endpoint/getAllDishs";
            String url = BASE_URL + "/getDishByWindowId?window_id="+window_id;
            System.out.println(url);

            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();

            try {
                Response response = client.newCall(request).execute();

                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    // 解析获取到的菜品列表
                    List<Dish> dishList = parseDishList(responseBody);
                    System.out.println("+++++++++"+dishList.toString());
                    return dishList;
                } else {
                    Log.e("GetAllDishs", "Error: " + response.code());
                    return null;
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("GetAllDishs", "Error: " + e.getMessage());
                return null;
            }
        }

        public class DishAdapter extends ArrayAdapter<Dish> {
            public DishAdapter(Context context, List<Dish> dishs) {
                super(context, R.layout.window_list_item_layout, dishs);
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                if (convertView == null) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.window_list_item_layout, parent, false);
                }


                // 添加编辑菜品按钮
                Button editButton = convertView.findViewById(R.id.editButton);

                // 获取此位置处的当前菜品
                Dish selectedDish = getItem(position);
                // 为编辑按钮设置单击监听器
                editButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 调用编辑对话框
                        showEditDishDialog(selectedDish);
                    }
                });

                Button deleteButton = convertView.findViewById(R.id.deleteButton);

                // 为编辑按钮设置单击监听器
                deleteButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        showDeleteConfirmationDialog(selectedDish);
                    }
                });


                Dish dish = getItem(position);

                ImageView imgv = convertView.findViewById(R.id.img);
                TextView text1 = convertView.findViewById(R.id.text1);
                TextView text2 = convertView.findViewById(R.id.text2);
                TextView text3 = convertView.findViewById(R.id.text3);
                TextView text4 = convertView.findViewById(R.id.text4);
                TextView text5 = convertView.findViewById(R.id.text5);
                TextView text6 = convertView.findViewById(R.id.text6);

                // 添加以下代码进行空值检查
                if (dish != null && dish.getImg() != null && !dish.getImg().isEmpty()) {
                    // 使用 Glide 加载图片到 ImageView
                    String imageUrl = "http://10.2.0.232:8080/dish_img/" + dish.getImg();

                    Glide.with(getContext())
                            .load(imageUrl)
                            .apply(new RequestOptions()
                                    .override(400, 400)  // 请替换为所需的宽度和高度
                                    .centerCrop()  // 或 .fitCenter()，根据需要选择
                            )
                            .listener(new RequestListener<Drawable>() {
                                @Override
                                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                    Log.e("GlideDebug", "Failed to load image: " + e.getMessage(), e);
                                    return false;
                                }

                                @Override
                                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                    Log.d("GlideDebug", "Image loaded successfully");
                                    return false;
                                }
                            })
                            .into(imgv);
                    imgv.setVisibility(View.VISIBLE);
                } else {
                    // 如果没有图片，隐藏 ImageView
                    imgv.setVisibility(View.GONE);
                }

                text1.setText("菜品名: " + dish.getDish_name());
                text2.setText("窗口名: " + dish.getWindow_name());
                text3.setText("价格: " + dish.getPrice());
                text4.setText("窗口id:" + dish.getWindow_id());
                text5.setText("菜单id:" + dish.getMenu_id());


                return convertView;
            }
        }

        @Override
        protected void onPostExecute(List<Dish> dishList) {
            if (dishList != null) {
                // 创建适配器
               DishAdapter adapter = new DishAdapter(getActivity(), dishList);

                // 将适配器设置到ListView
                dishListView.setAdapter(adapter);

                for (Dish dish : dishList) {
                    Log.d("DishInfo", "ID: " + dish.getDish_id() + ", Name: " + dish.getDish_name() +", Img: " + dish.getImg());
                    // 根据需要在界面上显示菜品信息
                }
            }
        }
    }

    private List<Dish> parseDishList(String responseBody) {
        // 实现解析JSON的逻辑，将数据转换成 Dish 对象列表
        // 这里需要根据您后端返回的数据格式进行解析
        List<Dish> dishList = new ArrayList<>();
        try {
            JSONArray jsonArray = new JSONArray(responseBody);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonDish = jsonArray.getJSONObject(i);
                Dish dish = new Dish();

                dish.setDish_name(jsonDish.getString("dish_name"));
                dish.setPrice(jsonDish.getString("price"));
                dish.setDish_id(jsonDish.getString("dish_id"));
                dish.setMenu_id(jsonDish.getString("menu_id"));
                dish.setWindow_id(jsonDish.getString("window_id"));
                dish.setWindow_name(jsonDish.getString("window_name"));

                dish.setImg(jsonDish.getString("img"));

                // 其他字段的解析
                dishList.add(dish);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return dishList;    }
    public void getAllDishs() {
        new GetAllDishsTask(window_id).execute();
    }




    private String getFileNameFromPath(String path) {
        if (path != null) {
            File file = new File(path);
            return file.getName();
        }
        return null;
    }




    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GET_FROM_GALLERY && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                // 获取所选图片的 URI
                Uri selectedImage = data.getData();

                // 获取图片路径
                selectedImagePath = getPathFromUri(selectedImage);

                // 设置isImageSelected为true
                isImageSelected = true;

                // 在这里可以根据需要处理选定的图片
            }
        }
    }

    private String getPathFromUri(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);

        if (cursor != null) {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String filePath = cursor.getString(columnIndex);
            cursor.close();
            return filePath;
        }

        return uri.getPath();
    }




    private void showAddDishDialog() {
        // 使用 AlertDialog.Builder 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("新增菜品");

        // 使用 LayoutInflater 加载自定义布局
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_add_dish, null);
        builder.setView(dialogView);

        // 获取对话框中的 EditText 和按钮
        final EditText etDishId = dialogView.findViewById(R.id.etDishId);
        final EditText etDishName = dialogView.findViewById(R.id.etDishName);
        final EditText etMenuId = dialogView.findViewById(R.id.etMenuId);
        final EditText etPrice = dialogView.findViewById(R.id.etPrice);
        final EditText etWindowId = dialogView.findViewById(R.id.etWindowId);
        final Button btnUploadImage = dialogView.findViewById(R.id.btnUploadImage);

        // 创建新的 ImageView 并将其添加到布局中
        ImageView selectedImageView = new ImageView(getActivity());
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        selectedImageView.setLayoutParams(layoutParams);
        ((LinearLayout) dialogView).addView(selectedImageView);

        // 点击上传图片按钮，启动选择图片的 Intent
        btnUploadImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 调用系统相册
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(intent, GET_FROM_GALLERY);
            }
        });


        // 设置对话框按钮
        builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 获取菜品输入的信息
                String dishId = etDishId.getText().toString();
                String menuID = etMenuId.getText().toString();
                String dishName = etDishName.getText().toString();
                String price = etPrice.getText().toString();
                String windowId = etWindowId.getText().toString();

                // 判断必填字段是否为空
                if (dishName.isEmpty() || price.isEmpty() || dishId.isEmpty()) {
                    Toast.makeText(getActivity(), "请填写所有字段", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 在这里执行添加菜品的操作，包括上传图片
                if (isImageSelected) {
                    // 获取选择的图片文件名
                    String selectedImageFileName = getFileNameFromPath(selectedImagePath);
                    String img = selectedImageFileName.toString();
                    System.out.println("+++++++++++++" + selectedImageFileName);

                    // 构建 Dish 对象
                    Dish newDish = new Dish(dishId, windowId, menuID, dishName, price, img);

                    // 添加菜品
                    new DishAddTask(dishId, windowId, menuID, dishName, price, selectedImagePath).execute(newDish);
                } else {
                    // 提示用户选择图片
                    Toast.makeText(getActivity(), "请先选择图片", Toast.LENGTH_SHORT).show();
                }
            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 菜品点击取消，不执行任何操作
            }
        });

        // 显示对话框
        AlertDialog alertDialog = builder.create();
        alertDialog.show();

        // 使用 Glide 加载图片到 ImageView
        if (selectedImagePath != null && selectedImageView != null) {
            Glide.with(requireActivity())
                    .load(selectedImagePath)
                    .into(selectedImageView);
            selectedImageView.setVisibility(View.VISIBLE);
        }



    }



    public class DishAddTask extends AsyncTask<Dish, Void, String> {

        private String dishId;
        private String windowId;
        private String menuId;
        private String dishName;
        private String price;
        private String imagePath;

        private String fileName; // 将 fileName 移到这里



        public DishAddTask(String dishId, String windowId, String menuId, String dishName, String price, String imagePath) {
            this.dishId = dishId;
            this.windowId = windowId;
            this.menuId = menuId;
            this.dishName = dishName;
            this.price = price;
            this.imagePath = imagePath;
            // 获取图片文件名
            File imageFile = new File(imagePath);
            this.fileName = imageFile.getName(); // 更新为成员变量
        }



        @Override
        protected String doInBackground(Dish... dishes) {
            OkHttpClient client = new OkHttpClient();

            // 构建请求体
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("dish_id", dishId)
                    .addFormDataPart("window_id", windowId)
                    .addFormDataPart("menu_id", menuId)
                    .addFormDataPart("dish_name", dishName)
                    .addFormDataPart("price", price)
                    .addFormDataPart("img", fileName, RequestBody.create(MediaType.parse("image/*"), new File(imagePath)))
                    .build();

            // 构建请求
            Request request = new Request.Builder()
                    .url(BASE_URL + "/addDish")
                    .post(requestBody)
                    .build();


            // 执行请求
            try {
                // 在客户端实例上使用 execute 方法
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    // 处理成功的响应
                    return response.body().string();
                } else {
                    // 处理失败的响应
                    return "Error: " + response.code();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "Error: " + e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            if (getActivity() != null) {
                // 处理结果，例如向菜品显示消息
                Log.d("AsyncTaskResult", "Result: " + result);
                Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();
                // 刷新菜品列表
                getAllDishs();
            }
        }
    }




    private void showEditDishDialog(Dish selectedDish) {
        // 使用 AlertDialog.Builder 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("编辑菜品");

        // 使用 LayoutInflater 加载自定义布局
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_add_dish, null);
        builder.setView(dialogView);

        // 获取对话框中的 EditText 和按钮的引用
        final EditText etDishId = dialogView.findViewById(R.id.etDishId);
        final EditText etDishName = dialogView.findViewById(R.id.etDishName);
        final EditText etMenuId = dialogView.findViewById(R.id.etMenuId);
        final EditText etPrice = dialogView.findViewById(R.id.etPrice);
        final EditText etWindowId = dialogView.findViewById(R.id.etWindowId);
        final Button btnUploadImage = dialogView.findViewById(R.id.btnUploadImage);

        // 点击上传图片按钮，启动选择图片的 Intent
        btnUploadImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 调用系统相册
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(intent, GET_FROM_GALLERY);
            }
        });

        // 创建新的 ImageView 并将其添加到布局中
        ImageView selectedImageView = new ImageView(getActivity());
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        selectedImageView.setLayoutParams(layoutParams);
        ((LinearLayout) dialogView).addView(selectedImageView);

        // 将选定的菜品的信息设置到相应的字段中
        etDishId.setText(selectedDish.getDish_id());
        etDishName.setText(selectedDish.getDish_name());
        etMenuId.setText(selectedDish.getMenu_id());
        etPrice.setText(selectedDish.getPrice());
        etWindowId.setText(selectedDish.getWindow_id());

        // 设置对话框按钮
        builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 获取用户输入的信息
                String dishId = etDishId.getText().toString();
                String menuID = etMenuId.getText().toString();
                String dishName = etDishName.getText().toString();
                String price = etPrice.getText().toString();
                String windowId = etWindowId.getText().toString();

                // 判断必填字段是否为空
                if (dishName.isEmpty() || price.isEmpty() || dishId.isEmpty()) {
                    Toast.makeText(getActivity(), "请填写所有字段", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 在这里执行编辑菜品的操作，包括上传新图片
                if (isImageSelected) {
                    // 获取选择的图片文件名
                    String selectedImageFileName = getFileNameFromPath(selectedImagePath);
                    String img = selectedImageFileName;

                    // 构建 Dish 对象
                    Dish editedDish = new Dish(dishId, windowId, menuID, dishName, price, img);

                    // 执行编辑菜品
                    new EditDishTask(dishId, windowId, menuID, dishName, price, selectedImagePath).execute(editedDish);
                } else {
                    // 如果没有选择新图片，仅更新菜品信息
                    Dish editedDish = new Dish(dishId, windowId, menuID, dishName, price, selectedDish.getImg());
                    new EditDishTask(dishId, windowId, menuID, dishName, price, null).execute(editedDish);
                }
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 取消编辑操作
            }
        });

        // 显示对话框
        AlertDialog alertDialog = builder.create();
        alertDialog.show();

        // 使用 Glide 加载图片到 ImageView
        if (selectedImagePath != null && selectedImageView != null) {
            Glide.with(requireActivity())
                    .load(selectedImagePath)
                    .into(selectedImageView);
            selectedImageView.setVisibility(View.VISIBLE);
        }
    }
    // 新增的编辑菜品的 AsyncTask
    private class EditDishTask extends AsyncTask<Dish, Void, String> {
        private String dishId;
        private String windowId;
        private String menuId;
        private String dishName;
        private String price;
        private String imagePath;

        public EditDishTask(String dishId, String windowId, String menuId, String dishName, String price, String imagePath) {
            this.dishId = dishId;
            this.windowId = windowId;
            this.menuId = menuId;
            this.dishName = dishName;
            this.price = price;
            this.imagePath = imagePath;
        }

        @Override
        protected String doInBackground(Dish... dishes) {
            OkHttpClient client = new OkHttpClient();

            // 构建请求体
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

            builder.addFormDataPart("dish_id", dishId)
                    .addFormDataPart("window_id", windowId)
                    .addFormDataPart("menu_id", menuId)
                    .addFormDataPart("dish_name", dishName)
                    .addFormDataPart("price", price);

            if (imagePath != null) {
                File imageFile = new File(imagePath);
                String fileName = imageFile.getName();
                builder.addFormDataPart("img", fileName, RequestBody.create(MediaType.parse("image/*"), new File(imagePath)));
            }

            RequestBody requestBody = builder.build();

            // 添加日志，记录请求的 URL、参数和头部信息
            String requestUrl = BASE_URL + "/editDish";
            String requestParams = "dishId=" + dishId + ", windowId=" + windowId + ", menuId=" + menuId +
                    ", dishName=" + dishName + ", price=" + price + ", imagePath=" + imagePath;

            System.out.println("Request URL: " + requestUrl);
            System.out.println("Request Params: " + requestParams);

            // 构建请求
            Request request = new Request.Builder()
                    .url(BASE_URL + "/editDish")
                    .post(requestBody)
                    .build();

            // 执行请求
            try {
                // 在客户端实例上使用 execute 方法
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    // 处理成功的响应
                    return response.body().string();
                } else {
                    // 处理失败的响应
                    return "Error: " + response.code();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "Error: " + e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            if (getActivity() != null) {
                // 处理结果，例如向菜品显示消息
                Log.d("AsyncTaskResult", "Server Response: " + result);
                Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();
                // 刷新菜品列表
                getAllDishs();
            }
        }
    }







    private void showDeleteConfirmationDialog(final Dish dishToDelete) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("确认删除");
        builder.setMessage("确定要删除菜品 " + dishToDelete.getDish_id() + " 吗？");

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 菜品确认删除，调用删除菜品的方法
                deleteDish(dishToDelete.getDish_id());
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 菜品取消删除
            }
        });

        builder.create().show();    }

    public void deleteDish(String dishId) {
        new DeleteDishTask().execute(dishId);
    }
    private class DeleteDishTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String dishId = params[0];
            OkHttpClient client = new OkHttpClient();
            String url = BASE_URL + "/deleteDish";

            // 构建 JSON 请求体
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            JSONObject json = new JSONObject();
            try {
                json.put("dish_id", dishId);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            RequestBody requestBody = RequestBody.create(JSON, json.toString());

            // 构建 HTTP 请求
            Request request = new Request.Builder()
//                    .url(url + "/" + dishId)
                    .url(url)
                    .post(requestBody)  // 使用 POST 请求，因为后端接口要求请求体
                    .build();

            try {
                // 执行请求
                Response response = client.newCall(request).execute();

                // 处理响应
                if (response.isSuccessful()) {
                    return response.body().string();
                } else {
                    return "Error: " + response.code();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "Error: " + e.getMessage();
            }
        }
        @Override
        protected void onPostExecute(String result) {
            if (getActivity() != null) {
                // 处理结果，例如向菜品显示消息
                Log.d("AsyncTaskResult", "Result: " + result);
                Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();
                // 刷新菜品列表
                getAllDishs();
            }
        }
    }
}
